package com.leyou.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSBuilder;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.upload.config.OSSProperties;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author hcz
 * @describtion TODO
 * @date 2019-06-25 18:49
 */
@Service
@Slf4j
public class UploadService {

    private static final List<String> suffixes =
            Arrays.asList("image/jpeg","image/jpg","image/png","image/bmp");

    public String upload(MultipartFile file) {

        //拿到上传的类型,并校验
        String fileType = file.getContentType();
        if (!suffixes.contains(fileType)) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }

        //校验图片内容
        //可以把它读出来看是否有效
        BufferedImage iamge = null;
        try {
            iamge = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            log.info("文件读取有问题！{}",e.getMessage());
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        if (iamge == null){
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        //保存图片
        //生成保存目录，保存到nginx所在目录的 html下，这样可以直接通过nginx来访问到
        File dir = new File("E:\\nginx-1.12.2\\html\\");
        if (!dir.exists()){
            dir.mkdirs();
        }
        try {
             //保存图片
            file.transferTo(new File(dir,file.getOriginalFilename()));
            //拼接图片地址
            return "http://image.leyou.com/"+file.getOriginalFilename();
        }catch (Exception e){
            throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
        }

    }


    @Autowired
    private OSS client;

    @Autowired
    private OSSProperties prop;

    public Map<String, Object> getSignature(){
        try {
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);
            return respMap;
        }catch (Exception e){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }
}
